package tf2pickup.listeners;

import tf2pickup.Players;

import java.util.ArrayList;
import java.util.HashMap;

import org.pircbotx.PircBotX;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.MessageEvent;

/** 
 *
 * @author Philipp Preß
 */
public class VoteMap extends ListenerAdapter<PircBotX> {

    private HashMap<String, Integer> maps;
    private Players players;

    public VoteMap(HashMap<String, Integer> maps, Players players) {
        this.maps = maps;
        this.players = players;
    }

    @Override
    public void onMessage(MessageEvent<PircBotX> event) {
        String input;
        String prevMapVote;
        ArrayList<String> matches;

        if (event.getMessage().toLowerCase().startsWith("!map ")) {
            //Check if the player who wants to vote is added to the pickup
            if (!players.containsPlayer(event.getUser().getNick())) {
                event.respond("Cannot vote for map: You have to be added to "
                        + "the pickup to vote for a map.");
                return;
            }
            input = event.getMessage().toLowerCase().substring(5).trim();
            prevMapVote = players.getPlayerProperties(event.getUser().getNick()).getMapVote();
            matches = new ArrayList<String>();
            //Put any map that matches with the input in the list
            for (String map : maps.keySet()) {
                if (map.contains(input)) {
                    matches.add(map);
                }
            }

            //Check if the list of matches is greater than one
            //(means the input is ambiguous)
            if (matches.size() != 1) {
                return;
            }

            //Check if the user has voted for a map already
            //If so, remove the vote
            if (!prevMapVote.isEmpty()) {
                maps.put(prevMapVote, maps.get(prevMapVote) - 1);
            }

            //Increasing mapvote for map by one
            maps.put(matches.get(0), maps.get(matches.get(0)) + 1);
            //Set mapVote for the player
            players.getPlayerProperties(event.getUser().getNick()).setMapVote(matches.get(0));
            //Refresh topic
            event.getBot().getListenerManager().dispatchEvent(
                    new MessageEvent<PircBotX>(event.getBot(), event.getChannel(), event.getUser(), "!status"));
        }
    }
}
